﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Application.Service.OrderInfo;
using Admin.NET.Application.Service.Position.Dto;
using Admin.NET.Application.Service.Tray.Dto;
using Admin.NET.Application.Service.Warehouse.Dto;
using Admin.NET.Core.Service.BarCode.Dto;
using AngleSharp.Dom;
using Aop.Api.Domain;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using Furion.Extensions;
using Furion.FriendlyException;
using Furion.Logging;
using Mapster;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HPSF;
using NPOI.Util;
using NewLife;
using DocumentFormat.OpenXml.Drawing.Diagrams;
using System.Runtime.Serialization;
using StackExchange.Redis;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using System.Data;
using RazorEngine.Compilation.ImpromptuInterface;
using WCS.Application.Entity.Warehous;


namespace Admin.NET.Application.Service.Warehouse;
/// <summary>
/// 仓库档案表
/// </summary>
[ApiDescriptionSettings(groups: ApplicationConst.GroupName, Order = 12)]
[AllowAnonymous]
public class WarehouseInfomationService : IDynamicApiController, ITransient
{

    //10001唯一过滤提示  10002 关于文件异常 10003 文件模板表头异常 10004导入异常提示

    /// <summary>
    /// 仓库档案实体
    /// </summary>
    private readonly SqlSugarRepository<WarehouseEntity> _warehouseEntity;
    /// <summary>
    /// 库位档案实体
    /// </summary>
    private readonly SqlSugarRepository<WarehousePositionEntity> _warehousePositionEntity;

    private readonly UserManager _userinfo;

    public WarehouseInfomationService(SqlSugarRepository<WarehouseEntity> WarehouseEntity, SqlSugarRepository<WarehousePositionEntity> WarehousePositionEntity, UserManager u)
    {
        _warehouseEntity = WarehouseEntity;
        _warehousePositionEntity = WarehousePositionEntity; _userinfo = u;


    }

    #region 仓库


    /// <summary>
    /// 获取仓库档案 
    /// </summary>
    /// <param name="warehouseInput"></param>
    /// <returns></returns>
    [DisplayName("获取仓库档案")]
    [ApiDescriptionSettings(Name = "GetWarehousePageList"), HttpPost]
    public async Task<SqlSugarPagedList<WarehouseEntity>> GetWarehousePageList(WarehouseInput warehouseInput)
    {

        var list = await _warehouseEntity.AsQueryable()
         .WhereIF(!string.IsNullOrWhiteSpace(warehouseInput.Name), u => u.Name.Contains(warehouseInput.Name.Trim()))
         .WhereIF(!string.IsNullOrWhiteSpace(warehouseInput.Code), u => u.Code == warehouseInput.Code.Trim())
         //.WhereIF(!string.IsNullOrWhiteSpace(warehouseInput.Isenable.ToString()), u =>Convert.ToInt32(u.Isenable).Equals(warehouseInput.Code))
         //.WhereIF(!string.IsNullOrWhiteSpace(warehouseInput.Isenable.ToString()), u => u.Isenable.Equals(warehouseInput.Isenable))

         .WhereIF(warehouseInput.Isenable.HasValue, u => u.Isenable == warehouseInput.Isenable)

         .WhereIF(!string.IsNullOrWhiteSpace(warehouseInput.CreateUserName), u => u.CreateUserName == warehouseInput.CreateUserName.Trim())
            //.WhereIF(DateTime.TryParse(warehouseInput.CreateTime.ToString()),  u => u.CreateTime > warehouseInput.CreateTime || u.UpdateTime < warehouseInput.UpdateTime)
            .OrderBuilder(warehouseInput)
            .ToPagedListAsync(warehouseInput.Page, warehouseInput.PageSize);

        //.WhereIF(!string.IsNullOrWhiteSpace(warehouseInput.Search.), u => u.Description.Contains(warehouseInput.Description.Trim()))
        var list2 = await _warehouseEntity.AsQueryable().ToPagedListAsync(warehouseInput.Page, warehouseInput.PageSize);

        return list;
    }
    /// <summary>
    /// 获取仓库信息 🔖
    /// </summary>
    /// <param name="warehouseInput"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "GetWarehouseList"), HttpPost]
    public async Task<List<WarehouseEntity>> GetWarehouseList(WarehouseInput warehouseInput)
    {
        Expression<Func<WarehouseEntity, bool>> expression = whereExp =>
                 (warehouseInput.Name.GetIsEmptyOrNull() || whereExp.Name.Contains((warehouseInput.Name.Trim())))
                 && (warehouseInput.Code.GetIsEmptyOrNull() || whereExp.Code.Contains((warehouseInput.Code.Trim())))
                 && (warehouseInput.CreateUserName.GetIsEmptyOrNull() || whereExp.CreateUserName.Equals(warehouseInput.CreateUserName))
                 && (warehouseInput.Isenable.GetIsEmptyOrNull() || whereExp.Isenable.Equals(warehouseInput.Isenable));

        var list = await _warehouseEntity.AsQueryable().WhereIF(expression != null, expression).ToListAsync();
        return list;
    }
    /// <summary>
    /// 添加仓库档案
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "InsertWarehouse"), HttpPost]
    public async Task<long> InsertWarehouse(AddWarehouseInput input)
    {
        #region 唯一索引
        Expression<Func<WarehouseEntity, bool>> whereExpression = whereExp =>
                    whereExp.Id.Equals(input.Id);
        #endregion
        var data = await _warehouseEntity.GetFirstAsync(whereExpression);
        if (data != null)
        {
            throw Oops.Oh(10001, "该记录已存在");
        }
        var entity = input.Adapt<WarehouseEntity>();
        await _warehouseEntity.AsInsertable(entity).ExecuteCommandAsync();
        return entity.Id;

    }

    /// <summary>
    /// 修改仓库档案
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "UpdateWarehouse"), HttpPost]
    public async Task UpdateWarehouse(WarehouseEntity input)
    {

        #region 唯一索引
        Expression<Func<WarehouseEntity, bool>> whereExpression = whereExp =>
                    whereExp.Id.Equals(input.Id);
        #endregion
        var data = await _warehouseEntity.GetFirstAsync(whereExpression);
        if (data == null)
        {
            throw Oops.Oh(10001, "该记录不存在");
        }

        try
        {

            if (data != null)
            {
                //对实体进行赋值
                input.UpdateUserId = _userinfo.UserId;
                input.UpdateTime = DateTime.Now;
                input.UpdateUserName = _userinfo.RealName;
            }
            else
            {


            }

        }
        catch (Exception error)
        {

            SerilogHelper.WriteLog("UpdateWarehouse失败" + error.Message);

            throw Oops.Oh("修改仓库档案出现错误：" + error.Message + "");
        }
        //api已转为entity
        await _warehouseEntity.AsUpdateable(input).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();

    }
    /// <summary>
    /// 删除仓库档案🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeleteWarehouse"), HttpPost]
    [DisplayName("删除仓库档案🔖")]
    public async Task DeleteWarehouse(DeleteWarehouseInput input)
    {
        #region 唯一索引
        Expression<Func<WarehouseEntity, bool>> whereExpression = whereExp =>
                    whereExp.Id.Equals(input.Id);
        #endregion

        var entity = await _warehouseEntity.GetFirstAsync(whereExpression) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        if (entity == null)
        {
            throw Oops.Oh("此库位还有余货请结清在删除");
        }
        else
        {
            await _warehouseEntity.DeleteAsync(entity); // 假删除
            //await _rep.DeleteAsync(entity); // 真删除
        }
    }





    /// <summary>
    /// 批量删除
    /// </summary>
    /// <param name="inputList"></param>
    /// <returns></returns>
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "BatchDeleteWarehouse"), HttpDelete]
    [DisplayName("批量删除")]
    public virtual async Task<int> BatchDeleteWarehouse(List<DeleteWarehouseInput> inputList)
    {
        #region "校验"
        foreach (var input in inputList)
        {
            Expression<Func<WarehouseEntity, bool>> whereExpression = whereExp =>
                        whereExp.Id.Equals(input.Id)
                   ;
            var data = await _warehouseEntity.GetFirstAsync(whereExpression);
            if (data == null)
            {
                throw Oops.Oh(10002, "该记录不存在");
            }

            // *****校验是否有其他表使用该记录*****
        }
        #endregion

        var deleteEntity = inputList.Adapt<List<WarehouseEntity>>();
        return await _warehouseEntity.AsDeleteable()
            .Where(deleteEntity)
            .ExecuteCommandAsync();
    }
    /// <summary>
    /// 下载模版
    /// </summary>
    /// <returns></returns>
    [UnitOfWork]
    [DisplayName("下载模版")]
    [ApiDescriptionSettings(Name = "DownloadWarehouse"), HttpGet]
    public virtual async Task<IActionResult> DownloadWarehouse()
    {
        #region "校验"
        string fileName = "WarehouseTemplate.xlsx";
        string filePath = $"{AppDomain.CurrentDomain.BaseDirectory}/Template/{fileName}";
        if (!File.Exists(filePath))
        {
            throw Oops.Oh(10002, "找不到该模板：" + filePath);
        }
        #endregion

        var path = Path.Combine(filePath);
        return new FileStreamResult(new FileStream(path, FileMode.Open), System.Net.Mime.MediaTypeNames.Application.Octet)
        {
            FileDownloadName = fileName
        };
    }

    /// <summary>
    /// 输出库位档案
    /// </summary>·
    [UnitOfWork]
    [DisplayName("输出")]
    [ApiDescriptionSettings(Name = "WarehouseExport"), HttpPost]
    public virtual async Task<IActionResult> WarehousePositExport(ExportWarehouseInput input)
    {


        Expression<Func<WarehouseEntity, bool>> whereExpression = whereExp =>
               (input.Name.GetIsEmptyOrNull() || whereExp.Name.Equals(input.Name))
               && (input.CreateUserName.GetIsEmptyOrNull() || whereExp.CreateUserName.Equals(input.CreateUserName))
               && (input.Code.GetIsEmptyOrNull() || whereExp.Code.Equals(input.Code))
               && (input.Isenable == 2 || (int)whereExp.Isenable == input.Isenable);
        //(int)warehouseInput.OrderStatus != 0 && Enum.IsDefined(typeof(OrderWStatusEnum), warehouseInput.OrderStatus), u => u.OrderStatus.Equals(warehouseInput.OrderStatus))

        var list = await _warehouseEntity.AsQueryable()
            .WhereIF(whereExpression != null, whereExpression).OrderBuilder(input
            )
            .ToListAsync();
        string path = AppDomain.CurrentDomain.BaseDirectory + "Export";
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        IExcelExporter excelExporter = new ExcelExporter();
        //设置列的内容格式
        //var exportOptions = new ExportOptions //ExportOptions
        //{

        //    ColumnFormats = new Dictionary<string, string>
        //    {
        //        { "TenantId", "@" }, // 设置为文本格式  
        //        { "CreateOrgId", "@" }, // 设置为文本格式  
        //        { "CreateUserId", "@" }, // 设置为文本格式  
        //        { "UpdateUserId", "@" }, // 设置为文本格式  
        //        { "Id", "@" }, // 设置为文本格式  
        //        { "CreateTime", "yyyy-MM-dd HH:mm:ss" }, // 设置为日期时间格式  
        //        { "Isenable", "0" } // 设置为数字格式  
        //    }

        //};
        var res = await excelExporter.ExportAsByteArray(list);

        return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = $"WarehouseExport_{DateTime.Now.ToString("yyyyMMddHHmmss")}_{new Random().Next(10000000, 99999999)}.xlsx" };

        //Table方式

        //var dataTable = await _warehouseEntity.AsQueryable()
        //    .WhereIF(whereExpression != null, whereExpression)
        //    .OrderBuilder(input)
        //    .SelectBuilder(input.TableHead)
        //    .ToDataTableAsync();

        //string path = AppDomain.CurrentDomain.BaseDirectory + "Export";
        //if (!Directory.Exists(path))
        //{
        //    Directory.CreateDirectory(path);
        //}
        //string fileName = $"WarehouseExport_{DateTime.Now.ToString("yyyyMMddHHmmss")}_{new Random().Next(10000000, 99999999)}.xlsx";
        //string filePath = path + @"/" + fileName;
        //ExcelHelper eh = new ExcelHelper(filePath);
        //eh.DataTableToExcel(dataTable);

        //return new FileStreamResult(new FileStream(filePath, FileMode.Open), System.Net.Mime.MediaTypeNames.Application.Octet)
        //{
        //    FileDownloadName = fileName
        //};
    }

    private WStatusEnum ParseStatusEnum(string value)
    {
        if (int.TryParse(value, out int numericValue))
        {
            // 如果是数字，直接转换为枚举
            return (WStatusEnum)numericValue;
        }
        else if (value == "启用" || value == "有货")
        {
            return WStatusEnum.Enable;
        }
        else if (value == "停用" || value == "无货")
        {
            return WStatusEnum.Disable;
        }
        else
        {
            throw new Exception($"无法解析的状态值: {value}");
        }
    }
    /// <summary>
    /// 导入
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [UnitOfWork]
    [DisplayName("导入")]
    [ApiDescriptionSettings(Name = "ImportWarehouse"), HttpPost]
    public virtual async Task<List<ImportWarehouseOutput>> ImportWarehouse([Required] IFormFile file)
    {

        if (file != null)
        {
            var fileDir = AppDomain.CurrentDomain.BaseDirectory + @"ImportFile";
            if (!Directory.Exists(fileDir))
            {
                Directory.CreateDirectory(fileDir);
            }
            //文件名称
            string fileName = file.FileName;
            //文件类型
            string fileType = file.FileName.Substring(fileName.LastIndexOf("."));
            //上传的文件的路径
            string filePath = fileDir + $@"/{fileName}";
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                file.CopyTo(fs);
            }

            if (fileType == ".xlsx" || fileType == ".xls")
            {
                ExcelHelper eh = new ExcelHelper(filePath);
                DataTable dt = eh.ExcelToDataTable("", true);
                eh.Dispose();
                if (dt == null || dt.Rows.Count == 0)
                {
                    throw Oops.Oh(10002, "文件为空！");
                }

                #region "校验模板字段"
                if (!dt.Columns.Contains("仓库名称") || !dt.Columns.Contains("仓库代码") || !dt.Columns.Contains("仓库描述") || !dt.Columns.Contains("是否启用") || !dt.Columns.Contains("备注"))
                {
                    throw Oops.Oh("文件模板错误！请重新下载模板");
                }
                #endregion

                List<ImportWarehouseOutput> listLoad = new List<ImportWarehouseOutput>();
                foreach (DataRow row in dt.Rows)
                {
                    ImportWarehouseOutput importWarehouse = new ImportWarehouseOutput
                    {
                        #region "字段"
                        Name = row["仓库名称"].GetCString(),
                        Code = row["仓库代码"].GetCString(),
                        Description = row["仓库描述"].GetCString(),
                        Isenable = ParseStatusEnum(row["是否启用"].GetCString())
                        #endregion
                    };

                    #region "校验必填项"

                    #endregion
                    //用唯一索引查询非重复
                    Expression<Func<WarehouseEntity, bool>> whereExpression = whereExp =>
                        whereExp.Code.Equals(importWarehouse.Code)
                    ;
                    var data = await _warehouseEntity.GetFirstAsync(whereExpression);
                    if (data == null)
                    {
                        //data = new WarehouseEntity();
                        data = _warehouseEntity.Adapt(importWarehouse);

                        #region "自定义校验"
                        data.CreateUserId = _userinfo.UserId;
                        data.CreateTime = DateTime.Now;
                        data.CreateUserName = _userinfo.RealName;
                        #endregion
                        var rtAdd = await _warehouseEntity.AsInsertable(data).ExecuteCommandAsync();
                        if (rtAdd != 1)
                        {
                            importWarehouse.ResultCode = 10004;
                            importWarehouse.Message = "插入失败";
                        }
                    }
                    else
                    {
                        #region "自定义校验"

                        #endregion

                        var rtUpdate = await _warehouseEntity.AsUpdateable(data).ExecuteCommandAsync();
                        if (rtUpdate != 1)
                        {
                            importWarehouse.ResultCode = 10004;
                            importWarehouse.Message = "更新失败";
                        }
                    }

                    if (importWarehouse.ResultCode != 200)
                        listLoad.Add(importWarehouse);
                }

                // 返回导入失败数据
                if (listLoad.Count > 0)
                {
                    return listLoad;
                }
            }
            else
            {
                throw Oops.Oh(10002, "文件内容为空！");
            }
        }
        else
        {
            throw Oops.Oh(10002, "请选择文件！");
        }
        return null;
    }


    #endregion


    #region 库位

    /// <summary>
    /// 获取库位档案server
    /// </summary>
    /// <param name="positionInput"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "GetWarehousePositPagelist"), HttpGet]
    public async Task<SqlSugarPagedList<WarehousePositionEntity>> GetWarehousePositPagelist([FromQuery] string data)
    {
        var positionInput = JsonConvert.DeserializeObject<PositionPositionInput>(data);


        var list = await _warehousePositionEntity.AsQueryable()
          .WhereIF(!string.IsNullOrWhiteSpace(positionInput.WarehousCode), u => u.WarehousCode.Contains(positionInput.WarehousCode.Trim()))
          .WhereIF(!string.IsNullOrWhiteSpace(positionInput.Code), u => u.Code == positionInput.Code.Trim())
          .WhereIF(!string.IsNullOrWhiteSpace(positionInput.Poiint), u => u.Poiint == positionInput.Poiint.Trim())
             .OrderBy(u => u.CreateTime, OrderByType.Desc)
             .ToPagedListAsync(positionInput.Page, positionInput.PageSize);
        //.WhereIF(!string.IsNullOrWhiteSpace(warehouseInput.Search.), u => u.Description.Contains(warehouseInput.Description.Trim()))


        return list;
    }

    // Fix for CS1061: Ensure the "Storey" property is accessed correctly and exists in the WarehousePositionEntity class.  
    // Fix for CS1061: Ensure the "OrderBuilder" method is correctly implemented or replaced with a valid alternative.  
    // Fix for CS1026: Ensure parentheses are properly closed in the code.  

    /// <summary>
    /// 获取位库档案 🔖
    /// </summary>
    /// <param name="warehouseInput"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "GetWarehousePositlist"), HttpPost]
    public async Task<List<WarehousePositionEntity>> GetWarehousePositlist(PositionPositionInput warehouseInput)
    {
        Expression<Func<WarehousePositionEntity, bool>> expression = whereExp =>
            (warehouseInput.Storey == null || whereExp.Storey == warehouseInput.Storey) // Ensure Storey is accessed correctly
            && (string.IsNullOrEmpty(warehouseInput.Code) || whereExp.Code.Equals(warehouseInput.Code))
            && (string.IsNullOrEmpty(warehouseInput.Poiint) || whereExp.Poiint.Equals(warehouseInput.Poiint))
            && (string.IsNullOrEmpty(warehouseInput.WarehousCode) || whereExp.WarehousCode.Contains(warehouseInput.WarehousCode));

        var list = await _warehousePositionEntity.AsQueryable()
            .WhereIF(expression != null, expression)
            .OrderBuilder(warehouseInput) // Replace OrderBuilder with OrderBy
            .ToListAsync();

        return list;
    }



    /// <summary>
    /// 添加库位档案
    /// </summary>
    /// <param name="positionInput"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "InsertWarehousePosit"), HttpPost]
    public async Task<long> InsertWarehousePosit(AddPositionInput input)
    {
        #region 唯一索引
        Expression<Func<WarehousePositionEntity, bool>> whereExpression = whereExp =>
                    whereExp.Id.Equals(input.Id);
        #endregion
        var data = await _warehousePositionEntity.GetFirstAsync(whereExpression);
        if (data != null)
        {
            throw Oops.Oh(10001, "该记录已存在");
        }

        var entity = input.Adapt<WarehousePositionEntity>();
        //entity.CreateUserId = _userinfo.UserId;
        entity.CreateTime = DateTime.Now;
        entity.Isenable = WStatusEnum.Enable;
        await _warehousePositionEntity.AsInsertable(entity).ExecuteCommandAsync();
        return entity.Id;

    }

    /// <summary>
    /// 修改库位档案
    /// </summary>
    /// <param name="warehousePosit"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "UpdateWarehousePosit"), HttpPut]
    public async Task UpdateWarehousePosit(WarehousePositionEntity warehousePosit)
    {
        #region 唯一索引
        Expression<Func<WarehousePositionEntity, bool>> whereExpression = whereExp =>
                    whereExp.Poiint.Equals(warehousePosit.Poiint);
        #endregion

        var entity = await _warehousePositionEntity.GetFirstAsync(whereExpression);

        try
        {
            if (entity != null)
            {
                //if (entity.Isenable == WStatusEnum.Disable)
                //{
                //    throw Oops.Oh("当前库位使用状态冻结");
                //}
                //else
                //{
                //对实体进行赋值
                warehousePosit.UpdateUserId = _userinfo.UserId;
                warehousePosit.UpdateTime = DateTime.Now;
                warehousePosit.UpdateUserName = _userinfo.RealName;
                warehousePosit.Code = warehousePosit.Code;
                warehousePosit.Id = entity.Id;
                //}
            }
            else
            {
                SerilogHelper.WriteLog("UpdateWarehouse修改记录不存在" + ErrorCodeEnum.D1002);
                throw Oops.Oh(ErrorCodeEnum.D1002);
            }
        }
        catch (Exception error)
        {
            SerilogHelper.WriteLog("UpdateWarehouse失败", error.Message);
            throw Oops.Oh("修改库位档案出现错误：" + error.Message + "");
        }
        var updateEntity = warehousePosit.Adapt<WarehousePositionEntity>();

        //api已转为entity
        await _warehousePositionEntity.AsUpdateable(updateEntity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();

    }

    /// <summary>
    /// 删除库位档案🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeletePosition"), HttpPost]
    [DisplayName("删除库位档案🔖")]
    public async Task DeletePosition(DeletePosInput input)
    {
        #region 唯一索引
        Expression<Func<WarehousePositionEntity, bool>> whereExpression = whereExp =>
                    whereExp.Id.Equals(input.Id);
        #endregion

        var entity = await _warehousePositionEntity.GetFirstAsync(whereExpression) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        if (entity.Isenable != WStatusEnum.Enable)
        {
            throw Oops.Oh("此库位还有余货请结清在删除");
        }
        else
        {
            await _warehousePositionEntity.DeleteAsync(entity); // 假删除
            //await _rep.DeleteAsync(entity); // 真删除
        }
    }
    /// <summary>
    /// 批量删除
    /// </summary>
    /// <param name="inputList"></param>
    /// <returns></returns>
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "BatchDeletePosition"), HttpDelete]
    [DisplayName("批量删除")]
    public virtual async Task<int> BatchDeletePosition(List<DeletePosInput> inputList)
    {
        #region "校验"
        foreach (var input in inputList)
        {
            Expression<Func<WarehousePositionEntity, bool>> whereExpression = whereExp =>
                        whereExp.Id.Equals(input.Id)
                   ;
            var data = await _warehousePositionEntity.GetFirstAsync(whereExpression);
            if (data == null)
            {
                throw Oops.Oh("该记录不存在");
            }

            // *****校验是否有其他表使用该记录*****
        }
        #endregion

        var deleteEntity = inputList.Adapt<List<WarehousePositionEntity>>();
        return await _warehousePositionEntity.AsDeleteable()
            .Where(deleteEntity)
            .ExecuteCommandAsync();
    }
    /// <summary>
    /// 下载模版
    /// </summary>
    /// <returns></returns>
    [UnitOfWork]
    [DisplayName("下载模版")]
    [ApiDescriptionSettings(Name = "DownloadWarehousePosit"), HttpGet]
    public virtual async Task<IActionResult> DownloadWarehousePosit()
    {
        #region "校验"
        string fileName = "WarehousePositTemplate.xlsx";
        string filePath = $"{AppDomain.CurrentDomain.BaseDirectory}/Template/{fileName}";
        if (!File.Exists(filePath))
        {
            throw Oops.Oh(10002, "找不到该模板：" + filePath);
        }
        #endregion

        var path = Path.Combine(filePath);
        return new FileStreamResult(new FileStream(path, FileMode.Open), System.Net.Mime.MediaTypeNames.Application.Octet)
        {
            FileDownloadName = fileName
        };
    }

    /// <summary>
    /// 输出库位档案
    /// </summary>·
    [UnitOfWork]
    [DisplayName("输出")]
    [ApiDescriptionSettings(Name = "WarehousePositExport"), HttpPost]
    public virtual async Task<IActionResult> WarehousePositExport(ExportPositionInput input)
    {
        Expression<Func<WarehousePositionEntity, bool>> whereExpression = whereExp =>
                   (input.WarehousCode.GetIsEmptyOrNull() || whereExp.WarehousCode.Equals(input.WarehousCode))
                   && (input.Code.GetIsEmptyOrNull() || whereExp.Code.ToLower().Contains(input.Code.ToLower().Trim()))
                   && (input.Poiint.GetIsEmptyOrNull() || whereExp.Poiint.Contains(input.Poiint.Trim()));

        var list = await _warehousePositionEntity.AsQueryable()
           .WhereIF(whereExpression != null, whereExpression)
           .ToListAsync();
        string path = AppDomain.CurrentDomain.BaseDirectory + "Export";
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        IExcelExporter excelExporter = new ExcelExporter();



        var res = await excelExporter.ExportAsByteArray(list);
        return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = $"WarehousePositExport_{DateTime.Now.ToString("yyyyMMddHHmmss")}_{new Random().Next(10000000, 99999999)}.xlsx" };

        //var dataTable = await _warehousePositionEntity.AsQueryable()
        //    .WhereIF(whereExpression != null, whereExpression)
        //    .OrderBuilder(input)
        //    .SelectBuilder(input.TableHead)
        //    .ToDataTableAsync();

        //string path1 = AppDomain.CurrentDomain.BaseDirectory + "Export";
        //if (!Directory.Exists(path1))
        //{
        //    Directory.CreateDirectory(path1);
        //}
        //string fileName = $"WarehousePositExport_{DateTime.Now.ToString("yyyyMMddHHmmss")}_{new Random().Next(10000000, 99999999)}.xlsx";
        //string filePath = path1 + @"/" + fileName;
        //ExcelHelper eh = new ExcelHelper(filePath);
        //eh.DataTableToExcel(dataTable);

        //return new FileStreamResult(new FileStream(filePath, FileMode.Open), System.Net.Mime.MediaTypeNames.Application.Octet)
        //{
        //    FileDownloadName = fileName
        //};
    }

    /// <summary>
    /// 导入
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [UnitOfWork]
    [DisplayName("导入")]
    [ApiDescriptionSettings(Name = "ImportWarehousePosit"), HttpPost]
    public virtual async Task<List<ImportPositionOutput>> ImportWarehousePosit([Required] IFormFile file)
    {

        if (file != null)
        {
            var fileDir = AppDomain.CurrentDomain.BaseDirectory + @"ImportFile";
            if (!Directory.Exists(fileDir))

            {
                Directory.CreateDirectory(fileDir);
            }
            //文件名称
            string fileName = file.FileName;
            //文件类型
            string fileType = file.FileName.Substring(fileName.LastIndexOf("."));
            //上传的文件的路径
            string filePath = fileDir + $@"/{fileName}";
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                file.CopyTo(fs);
            }

            if (fileType == ".xlsx" || fileType == ".xls")
            {
                ExcelHelper eh = new ExcelHelper(filePath);
                DataTable dt = eh.ExcelToDataTable("", true);
                eh.Dispose();
                if (dt == null || dt.Rows.Count == 0)
                {
                    throw Oops.Oh("文件为空！");
                }

                #region "校验模板字段"
                if (!dt.Columns.Contains("库位编码") || !dt.Columns.Contains("仓库代码") || !dt.Columns.Contains("点位") || !dt.Columns.Contains("是否启用") || !dt.Columns.Contains("通道位置") || !dt.Columns.Contains("楼层"))
                {
                    throw Oops.Oh("文件模板错误！请重新下载模板");
                }
                #endregion

                List<ImportPositionOutput> listLoad = new List<ImportPositionOutput>();
                int i = 0;
                foreach (DataRow row in dt.Rows)
                {
                    i++;
                    //校验关联信息是否正确仓库代码
                    var warehouseCodeList = await GetWarehouseList(new WarehouseInput { Code = row["仓库代码"].GetCString(), Isenable = WStatusEnum.Enable });
                    if (warehouseCodeList.Count() < 1)
                    {
                        throw Oops.Oh($"文件内容填写出错！第{i}行仓库代码列没有{row["仓库代码"].GetCString()}请重新填写");

                    }

                    ImportPositionOutput importPosition = new ImportPositionOutput
                    {
                        #region "字段"
                        Code = row["库位编码"].GetCString(),
                        WarehousCode = row["仓库代码"].GetCString(),
                        Poiint = row["点位"].GetCString(),
                        ChannelLocation = row["通道位置"].GetCString(),
                        Storey = row["楼层"].GetCInt(),
                        Isenable = ParseStatusEnum(row["是否启用"].GetCString()),
                        //Available = ParseStatusEnum(row["是否有货"].GetCString())
                        #endregion
                    };
                    #region "校验必填项"

                    #endregion
                    //用唯一索引查询非重复
                    Expression<Func<WarehousePositionEntity, bool>> whereExpression = whereExp =>
                        whereExp.Code.Equals(importPosition.Code);
                    var data = await _warehousePositionEntity.GetFirstAsync(whereExpression);
                    if (data == null)
                    {
                        #region "自定义校验"
                        data.CreateTime = DateTime.Now;
                        data.CreateUserId = _userinfo.UserId;
                        data.CreateUserName = _userinfo.RealName;
                        data = importPosition.Adapt(importPosition);
                        #endregion

                        var rtAdd = await _warehousePositionEntity.AsInsertable(data).ExecuteCommandAsync();
                        if (rtAdd != 1)
                        {
                            importPosition.ResultCode = 10004;
                            importPosition.Message = "插入失败";
                        }
                    }
                    else
                    {
                        #region "自定义校验"
                        data.UpdateUserId = _userinfo.UserId;
                        data.UpdateTime = DateTime.Now;
                        data.UpdateUserName = _userinfo.RealName;

                        #endregion
                        data.Code = importPosition.Code;
                        data.WarehousCode = importPosition.WarehousCode;
                        data.Poiint = importPosition.Poiint;
                        data.Isenable = importPosition.Isenable;
                        //data.Available = importPosition.Available;


                        //不能用Adapt替换因为importPosition中没主键
                        //data = data.Adapt(importPosition, config);
                        //data = importPosition.Adapt(data);


                        var rtUpdate = await _warehousePositionEntity.AsUpdateable(data).ExecuteCommandAsync();
                        if (rtUpdate != 1)
                        {
                            importPosition.ResultCode = 10004;
                            importPosition.Message = "更新失败";
                        }
                    }

                    if (importPosition.ResultCode != 200)
                        listLoad.Add(importPosition);
                }

                // 返回导入失败数据
                if (listLoad.Count > 0)
                {
                    return listLoad;
                }
            }
            else
            {
                throw Oops.Oh(10002, "文件内容为空！");
            }
        }
        else
        {
            throw Oops.Oh(10002, "请选择文件！");
        }
        return null;
    }

    #endregion

}
